# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head is None:
            return head
        middle=[head]
        listnode=None
        head=head.next
        while head is not None:
            if listnode is not None:
                if listnode.val!=head.val:
                    listnode=None
                    middle.append(head)
            else:
                if len(middle)==0:
                    middle.append(head)
                elif middle[-1].val!=head.val:
                    middle.append(head)
                else:
                    middle.pop(-1)
                    listnode=head
            head=head.next
        middle.append(None)
        head=middle[0]
        for i in range(len(middle)-1):
           middle[i].next=middle[i+1]
        return head

